package com.tree.rw.demo.bean;

import com.tree.rw.demo.enums.DBTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName com.tree.rw.demo.bean
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 2019-06-02 13:56
 * @Version 1.0
 */
public class DBContextHolder {

    private static final ThreadLocal<DBTypeEnum> holder = new ThreadLocal<>();

    private static final AtomicInteger counter = new AtomicInteger(-1);


    public static void setDBHolder(DBTypeEnum dbTypeEnum){
        holder.set(dbTypeEnum);
    }

    public static DBTypeEnum getDBHolder(){
        return holder.get();
    }

    /**
     * 设置数据源,判断传进来的主库还是从库的类型
     * @param dbTypeEnum
     */
    public static void setDataSource(DBTypeEnum dbTypeEnum){
        if(DBTypeEnum.MASTER == dbTypeEnum){
            master();
        }else{
            roundSlave();
        }
    }

    public static void master(){
        setDBHolder(DBTypeEnum.MASTER);
        System.err.println("===========switch to master datasource");
    }

    /**
     * TODO 可以根据相关负载均衡算法路由到任意一台Slave服务器
     * 比如说如下利用atomic%2来简单轮询Slave1，Slave2
     */
    public static void roundSlave(){
        //
//        //计数器模运算
//        Integer index = counter.getAndIncrement() % 2;
//        //计数器重置
//        if (counter.get() > 9999) {
//            counter.set(-1);
//        }
//        if (index == 0) {
//            setDBHolder(DBTypeEnum.SLAVE1);
//            System.out.println("切换到slave1");
//        }else {
//            setDBHolder(DBTypeEnum.SLAVE2);
//            System.out.println("切换到slave2");
//        }
        setDBHolder(DBTypeEnum.SLAVE1);
        System.err.println("===========switch to slave1 datasource");
    }

}
